package hk.ust.cse.comp3111.studentSchedule;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ImportByCourse extends Fragment implements OnClickListener{
	
	TextView courseCodeTextStatic ;
	AutoCompleteTextView tv;
	CourseDatabaseHandler db;
	RegisteredClassDatabaseHandler db_register;
	List<String> courseCode;
	ArrayList<String> listItems;
	ArrayAdapter<String> adapter;
	Button selectButton;
	Button importButton;
	
	TextView courseCodeInput, title,textView2,lecture,tutorial,labortatory;
	Spinner lectureSpinner, tutorialSpinner, labSpinner;

	long calendarID;
	long eventID;
	
	 private String array_spinner[];
	
	public ImportByCourse(){}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.import_by_course, container, false);
         
        return rootView;
    }
	

  

	@Override
	public void onStart() {
		super.onStart();
		db=new CourseDatabaseHandler(this.getActivity());
		selectButton= (Button) this.getView().findViewById(R.id.selectButton);
		selectButton.setOnClickListener(this);
		importButton=(Button) this.getView().findViewById(R.id.importButton);
		
		courseCodeTextStatic = (TextView) this.getView().findViewById(R.id.courseCodeText);
		tv = (AutoCompleteTextView) this.getView().findViewById(R.id.courseCodeInput);
		List<String> courseCode = db.getAllCourseCode();
		ArrayList<String> listItems=new ArrayList<String>();
		
		for(String s : courseCode){
        	listItems.add(s);
        }
		
		
		//ListView myListView = (ListView) this.getView().findViewById(R.id.list);
        
        adapter=new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_dropdown_item_1line,listItems);
        
        tv.setAdapter(adapter);
        
	
        courseCodeInput = (TextView) this.getView().findViewById(R.id.courseCode);
		title = (TextView) this.getView().findViewById(R.id.title);
		textView2= (TextView) this.getView().findViewById(R.id.textView2);
		lecture= (TextView) this.getView().findViewById(R.id.lecture);
		tutorial= (TextView) this.getView().findViewById(R.id.tutorial);
		labortatory= (TextView) this.getView().findViewById(R.id.lab);
		
		lectureSpinner  =  (Spinner) this.getView().findViewById(R.id.lectureSpinner);
		tutorialSpinner =  (Spinner) this.getView().findViewById(R.id.tutorialSpinner);
		labSpinner		=  (Spinner) this.getView().findViewById(R.id.labSpinner);
		
		
		
		courseCodeInput.setVisibility(View.INVISIBLE);
		title.setVisibility(View.INVISIBLE);
		lectureSpinner.setVisibility(View.INVISIBLE);
		tutorialSpinner.setVisibility(View.INVISIBLE);
		labSpinner.setVisibility(View.INVISIBLE);
		textView2.setVisibility(View.INVISIBLE);
		lecture.setVisibility(View.INVISIBLE);
		tutorial.setVisibility(View.INVISIBLE);
		labortatory.setVisibility(View.INVISIBLE);
		importButton.setVisibility(View.INVISIBLE);
	
	}

	
	@Override
	public void onClick(View v) {
		
		
		String input = tv.getText().toString().toUpperCase();
		db=new CourseDatabaseHandler(this.getActivity());
		//List<Course> courseList = new ArrayList();
		//courseList = db.getCourseByCourseCode(input);
		
		//List<String> outout = new ArrayList<String>();
		//outout = db.test();
		List<String> courseCodeTest = db.getAllCourseCode();
		List<Course> courseInfo = db.getCourseByCourseCode(tv.getText().toString().toUpperCase());
		lecture.setVisibility(View.VISIBLE);
		tutorial.setVisibility(View.VISIBLE);
		labortatory.setVisibility(View.VISIBLE);
		
		
		courseCodeTextStatic.setVisibility(View.INVISIBLE);
		selectButton.setVisibility(View.INVISIBLE);
		tv.setVisibility(View.INVISIBLE);
		String test=tv.getText().toString();
		textView2.setText("Select your class of "+tv.getText().toString().toUpperCase());
		textView2.setVisibility(View.VISIBLE);
        
        String[] lecture = {"L1", "L2"};
        String[] tut = {"T1", "T2", "T3"};
        String[] lab = {"LA1", "LA2", "LA3"};
        
        List<String> lectureMemory= new ArrayList<String>();
        List<String> tutMemory= new ArrayList<String>();
        List<String> labMemory= new ArrayList<String>();
        for (Course c : courseInfo){
        	switch(c.getType()){
        	case 1:
        		lectureMemory.add(c.getSection());
        		break;
        	case 2:
        		tutMemory.add(c.getSection());
        		break;
        	case 3:
        		labMemory.add(c.getSection());
        		break;
        	}
        	
        }
        String[] lectureMem = lectureMemory.toArray(new String[lectureMemory.size()]);
        String[] tutMem = tutMemory.toArray(new String[tutMemory.size()]);
        String[] labMem = labMemory.toArray(new String[labMemory.size()]);
        
      
        ArrayAdapter<CharSequence> adapter =    new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_item,lectureMem);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        lectureSpinner.setAdapter(adapter);
        
        ArrayAdapter<CharSequence> tutorial =    new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_item,tutMem);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        tutorialSpinner.setAdapter(tutorial);

        ArrayAdapter<CharSequence> labor_ =    new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_item,labMem);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        labSpinner.setAdapter(labor_);
        
        
		
        lectureSpinner.setVisibility(View.VISIBLE);
		tutorialSpinner.setVisibility(View.VISIBLE);
		labSpinner.setVisibility(View.VISIBLE);
		
		importButton.setVisibility(View.VISIBLE);
		importButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				addEvent(tv.getText().toString().toUpperCase(), lectureSpinner.getSelectedItem().toString());
				addEvent(tv.getText().toString().toUpperCase(), tutorialSpinner.getSelectedItem().toString());
				addEvent(tv.getText().toString().toUpperCase(), labSpinner.getSelectedItem().toString());
			}
			
		});
		
		
		
	}
	
	
	private void addEvent(String courseCode, String section) {
		
		db=new CourseDatabaseHandler(this.getActivity());
		Course course = db.getCourseByCourseCodeAndSection(courseCode, section);
		int loop=0;
		String ruleSub=new String();
		String WEEKDAY[]={"MO","TU","WE","TH","FR"};
		
		if(course.getRep3_weekDay()!=0){
			loop=3;
			//ruleSub=WEEKDAY[(int) (course.getRep1_weekDay()-1)]+","+WEEKDAY[(int) course.getRep2_weekDay()-1]+","+WEEKDAY[(int) course.getRep3_weekDay()];
		}
		else if (course.getRep2_weekDay()!=0){
			loop=2;
			//ruleSub=WEEKDAY[(int) (course.getRep1_weekDay()-1)]+","+WEEKDAY[(int) course.getRep2_weekDay()-1];
		}
		else if (course.getRep1_weekDay()!=0){
			loop=1;
			//ruleSub=WEEKDAY[(int) (course.getRep1_weekDay()-1)];
		}
		
		//long resu=course.getFromDate().getTime()+course.getRep1_fromTime()+j*604800000L;
		//Toast.makeText(getActivity(),"time check "+course.getFromDate().getTime()+course.getRep1_fromTime()+0*604800000,Toast.LENGTH_LONG).show();
		
		
		//Toast.makeText(getActivity(),"loop: "+loop,Toast.LENGTH_LONG).show();
		
		db_register=new RegisteredClassDatabaseHandler(this.getActivity());
		//db_register.register(course);

		
		//String duration="P"+Long.toString((course.getRep1_toTime()-course.getRep1_fromTime())/1000)+"S";
		//Toast.makeText(getActivity(),"duration: "+duration,Toast.LENGTH_LONG).show();
		
		for(int i=1; i<=loop; i++){
			if(i==1){
						
				String duration="P"+Long.toString((course.getRep1_toTime()-course.getRep1_fromTime())/1000)+"S";
				
					put(course.getCourseCode()+" "+course.getSection() ,
						course.getFromDate().getTime()+course.getRep1_fromTime(),
						course.getVenue(),
						duration
							);
				
			}
			
			else if (i==2){
				
				String duration="P"+Long.toString((course.getRep2_toTime()-course.getRep2_fromTime())/1000)+"S";
				long difference=(course.getRep2_weekDay()-course.getRep1_weekDay())*86400000L;
				
				put(course.getCourseCode()+" "+course.getSection() ,
						course.getFromDate().getTime()+course.getRep2_fromTime()+difference,
						course.getVenue(),
						duration
							);
				
			}
			
			else if (i==3){
	
				String duration="P"+Long.toString((course.getRep3_toTime()-course.getRep3_fromTime())/1000)+"S";
				long difference=(course.getRep2_weekDay()-course.getRep1_weekDay())*86400000L;
				
				put(course.getCourseCode()+" "+course.getSection() ,
						course.getFromDate().getTime()+course.getRep3_fromTime()+difference,
						course.getVenue(),
						duration
							);
				
			}
		}
		
    	
    }
 // we use this method in order to get the ID of the calendar because
 // calendar ID is a required field in creating an event
    
    public long getCalendarID() {
    	Cursor cur = null;
    	try {
    	// provide CalendarContract.Calendars.CONTENT_URI to
    	// ContentResolver to query calendars
    		cur = this.getActivity().getContentResolver().query(CalendarContract.Calendars.CONTENT_URI,null,null,null, null);
    		if (cur.moveToFirst()) {
    			return cur.getLong(cur.getColumnIndex(CalendarContract.Calendars._ID));
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		} finally {
		    	if (cur != null) {
		    	cur.close();
		    	}
    		}
    	return -1L;
    	}
	
	
	private void put(String title, long startTime, String venue,String duration){
		String rules = "FREQ=WEEKLY;COUNT=14";
		
		calendarID = getCalendarID();	
    	ContentValues eventValues = new ContentValues ();
    	eventValues.put(CalendarContract.Events.CALENDAR_ID,calendarID);
    	eventValues.put (CalendarContract.Events.TITLE,title);
    	eventValues.put (CalendarContract.Events.DESCRIPTION,"Added by Student Schedule");
    	eventValues.put(CalendarContract.Events.DTSTART,startTime);
    	eventValues.put(CalendarContract.Events.DURATION, duration);
    	eventValues.put(CalendarContract.Events.RRULE, rules);
    	eventValues.put(CalendarContract.Events.EVENT_LOCATION,venue);
    	eventValues.put(CalendarContract.Events.EVENT_TIMEZONE,TimeZone.getDefault().toString());
    	Uri eventUri = this.getActivity().getContentResolver().insert(CalendarContract.Events.CONTENT_URI, eventValues);
    	eventID = ContentUris.parseId(eventUri);
	}
	
	

	
	
}
